from flask import g, request, current_app, session

from app import auth, constants, db
from . import api
from app.models import User
from libs.error_code import NotFound, MethodError, AuthFailed, ServerError, \
                                Success, BadReuest, LoginError
from app.tasks import update_token
import functools

@api.app_errorhandler(400)
def bad_request(error):
    return BadReuest(message='发生错误,请联系管理员')


@api.app_errorhandler(404)
def page_not_found(error):
    return NotFound(message=u'无效页面')


@api.app_errorhandler(405)
def method_not_allowed(error):
    return MethodError()


@api.app_errorhandler(401)
def token_forbidden(error):
    return AuthFailed(message=u'无效token')


@api.app_errorhandler(500)
def server_error(error):
    return ServerError(message=u'服务器出错啦，请联系管理员')

def login_required(f):
    @functools.wraps(f)
    def wrapper(*args, **kwargs):
        user_id = session.get('user_id')
        db_user = db.session.query(User).filter(User.id == user_id).first()
        if db_user is not None:
            print(user_id, "is equal ", db_user.id)
            g.user_id = user_id
            print(g.user_id)
            return f(*args, **kwargs)
        else:
           return LoginError(message="用户未登录")
    return wrapper


@auth.verify_token
def verify_token(token):
    token = token.split(',')[0]
    g.current_user = User.verify_auth_token(token)
    g.token_used = True

    return g.current_user is not None


@api.route('/token', methods=['POST'])
def get_auth_token():
    user = User.login_verify(request.json)
    if not user:
        print("新用户..注册中")
        username = request.json.get('account')
        password = request.json.get('password')
        user_info = current_app.auth_token.verifyLogin(username=username, password=password)
        if user_info.get('status') == 1:
            user = User.query.filter(User.account == username).first()
            if not user:
                user = User(name=user_info.get('name'), account=username)
                user.email = f'{username}@thundersoft.com'
                user.password = password
                user.type = 'in'
                user.token = user_info.get('token')
                db.session.add(user)
                db.session.commit()
                print('注册成功')
    if user and user.type == 'in':
        print("更新token")
        update_token.delay(json_post=request.json, user_id=user.id)

    if user:
        exp = constants.EXPIRATION
        token = user.generate_auth_token(expiration=exp)
        # microse_token = user.get_microse_token(request.json) or user.token
        microse_token = user.token
        data = {
            'user': user.to_json(),
            'token': token,
            'microse_token': microse_token,
            'exp': exp
        }
        return Success(data=data)
    return AuthFailed(data={'status': 0})
